package com.atom.module.mvvm.extren

import androidx.annotation.CheckResult
import androidx.core.widget.NestedScrollView
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun NestedScrollView.scrollChangeEvents()  = callbackFlow<ScrollChangeEvent> {
    checkMainThread()
    val listener = NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
        trySend(
            ScrollChangeEvent(
                view = v,
                scrollX = scrollX,
                scrollY = scrollY,
                oldScrollX = oldScrollX,
                oldScrollY = oldScrollY
            )
        )
    }
    setOnScrollChangeListener(listener)
    awaitClose { setOnScrollChangeListener(null as NestedScrollView.OnScrollChangeListener?) }
}.conflate()

